package net.cyndeline.GUI.graphics

import net.cyndeline.GUI.GraphicsBuffer
import javafx.scene.image.Image
import net.cyndeline.GUI.GameObjectKey
import java.io.File
import net.cyndeline.misc.ResourceLoader

/**
 * Retrieves images from file. If the image has already been read
 * into memory, it is served from the buffer. Otherwise, an initial
 * image is read directly from file and served, then buffered for
 * future use.
 */
class GFXBuffer extends GraphicsBuffer {
  private var buffer = Map[String, Option[Image]]()
  
  override def get(key: String): Image = {
    val bufferedCopy = buffer.get(key)
    val result = if (bufferedCopy.isDefined) {
      buffer(key).get
    } else {
      val tmp = read(key)
      buffer += (key -> Option(tmp))
      tmp
    }
    result
  }
  
  override def get(key: String, frame: Int): Image = {
    get(key)
  }
  
  def read(key: String): Image = {
    if (key.matches(GameObjectKey.castle_floor)) {
      new Image(ResourceLoader.load("img/tile_placeholder.png"))
      
    } else if (key.matches(GameObjectKey.castle_wall_front)) {
      new Image(ResourceLoader.load("img/wall_placeholder.png"))
    } else if (key.matches(GameObjectKey.player)){
      new Image(ResourceLoader.load("img/hero_placeholder.png"))
    } else {
      new Image(ResourceLoader.load("img/tile_placeholder.png"))
    }
  }

}

object GFXBuffer {
  def read: GFXBuffer = new GFXBuffer()
}